<?php
class BrandController extends AppController {

	public $name = 'brand';
	function beforeFilter() {
	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; //For override login
	    $this->C_auth->allowedActions = array('categorieslist','categoriesadd','categoriesedit','categoriesdel','getcatbrandlist');

	}
	
	public function categorieslist() {
        $page = intval(Request::get_args('page'));
        $url_this = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        $tb = array('model' => 'brand',
 		            //'joins' => array('type'=>'left','table'=>'shoprequest','conditions'=>array('shopinfo.user_id' =>'shoprequest.user_id')),
				    'fields' => array('brand.*'),
					'conditions' => array(),
					'order' => 'brand.id desc',
					'limit' => '10',
					'group' => '',
					'url' => preg_replace("/&page=([^&]+)/","",$url_this),
					'page' => $page,
					'plist' => 6				
				); 
	    $result =  $this->fpage($tb); 		
        $this->set('result',$result);			
	}	
	public function categoriesadd() {        		
		if (!empty($this->data)) {
            Loader::import('lib.cupload'); 
            $upload_1 = new upload('jpg|gif|png',1024,'logo');
            $upload_1->set_dir(APP_ROOT . Param::read('upfiles.path') . '/brand/',"{y}/{m}/{d}");
            $file_1 = $upload_1->execute();
			    $rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
                $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';			
            if(count($file_1)>0) {
	            $this->data['brand']['brand_logo'] = $rootpath.str_replace(APP_ROOT,"",$file_1[0]['dir']).$file_1[0]['name'];
            }	
			$query = $this->data;
			if ($insertid = POP::exe('[@@:UM brand][@@:QU save]',$query)) {
				foreach($this->data['cat'] as $k=>$v) {
					$safeData = array();
					$safeData['brandgoodscategories']['brand_id'] = $insertid;
					$safeData['brandgoodscategories']['category_id'] = $v['cat_id']; 
					POP::exe('[@@:UM brandgoodscategories][@@:QU save]',$safeData);
				}	
				$this->flash('更新成功！', Router::url('admin/brand/categorieslist'));		
			} else {
				$this->flash('更新失败！', Router::url('admin/brand/categorieslist'));
			}				
			 	
	    } else {
			$query = array(
				'fields' => array('goodscategories.*'),
                'order' => 'sort_order asc,id asc'				
			);
			$result_category = POP::exe('[@@:UM goodscategories][@@:QU find:all]',$query);		
		    $category_dg = $this->get_dg_category($result_category);
            $this->set('category_dg',$category_dg);	
		}

	}

	public function getcatbrandlist() {	
        $cat_id = intval($_POST['cat_id']);
        if(!$cat_id) {
	        exit();
        }		
        header('Content-Type: text/html; charset='.Param::read('App.encoding'));		
		$query = array(
				'joins' => array(
					array('type'=>'left','table'=>'brandgoodscategories','conditions'=>array('brandgoodscategories.brand_id' =>'brand.id')),					
					),
				'fields' => array('brand.id'),
				'conditions' => array('brandgoodscategories.category_id' =>$cat_id),
				'group' => ' brand.id DESC '
				);	
	    $list = POP::exe('[@@:UM brand][@@:QU find:all]',$query);		
	    echo json_encode($list);
		exit;
	}		

	
	public function categoriesedit($id) {        
		if (!empty($this->data)) {			
            Loader::import('lib.cupload'); 
            $upload_1 = new upload('jpg|gif|png',1024,'logo');
            $upload_1->set_dir(APP_ROOT . Param::read('upfiles.path') . '/brand/',"{y}/{m}/{d}");
            $file_1 = $upload_1->execute();
			    $rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
                $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';			
            if(count($file_1)>0) {
	            if($file_1[0]['flag']==1) {
	                $brand_row = $this->brand->find('first', array('conditions' => array('brand.id' => $id)));
		            $logo_dir = Param::read('wwwrootPatch') . $brand_row['brand']['brand_logo'];
		            if(file_exists($logo_dir)){
			            @unlink($logo_dir);
		            }
                    $this->data['brand']['brand_logo'] = $rootpath.str_replace(APP_ROOT,"",$file_1[0]['dir']).$file_1[0]['name'];
	            }
/*                 $this->brand->create();
                $this->brand->id = $id;	 */				
            }

			$query['keyid'] = $id;
			$query['set'] = $this->data;
			if (POP::exe('[@@:UM brand][@@:QU save]',$query)) {				
				$query = array('conditions'=>array('brandgoodscategories.brand_id' => $id));			
				POP::exe('[@@:UM brandgoodscategories][@@:QU del]',$query);					
				foreach($this->data['cat'] as $k=>$v) {
					$safeData = array();
					$safeData['brandgoodscategories']['brand_id'] = $id;
					$safeData['brandgoodscategories']['category_id'] = $v['cat_id']; 
					POP::exe('[@@:UM brandgoodscategories][@@:QU save]',$safeData);					
				}	
				$this->flash('更新成功！', Router::url('admin/brand/categorieslist'));		
			} else {
				$this->flash('更新失败！', Router::url('admin/brand/categorieslist'));
			}				
			 	
	    }else {
			$query = array(
				'fields' => array('goodscategories.*'),
                'order' => 'sort_order asc,id asc'				
			);
			$result_category = POP::exe('[@@:UM goodscategories][@@:QU find:all]',$query);			
			
		    $category_dg = $this->get_dg_category($result_category);
			
			$query = array(
				'conditions' => array('brand.id' => $id), 
				'fields' => array('brand.*'), 
			);
			$brand_list = POP::exe('[@@:UM brand][@@:QU find:first]',$query);				
			$info = $brand_list['brand'];
			
			$query = array(
				'conditions' => array('brandgoodscategories.brand_id' => $id), 
				'fields' => array('brandgoodscategories.*'), 
			);
			$list = POP::exe('[@@:UM brandgoodscategories][@@:QU find:all]',$query);				
            $category_brand_list=array();
            if (is_array($list)) {
	            foreach ($list as $value){
		            $category_brand_list[]=$value['brandgoodscategories']['category_id'];
	            }
            }
		    $this->set('info',$info);	
            $this->set('category_dg',$category_dg);	
			$this->set('category_brand_list',$category_brand_list);
		}
		
	}
	
	public function categoriesdel($id) {
		$query = array('keyid'=>$id);			
        if(POP::exe('[@@:UM brand][@@:QU del]',$query)	) {
			$query = array('conditions'=>array('brandgoodscategories.brand_id' => $id));			
			POP::exe('[@@:UM brandgoodscategories][@@:QU del]',$query);			
		    $this->flash('删除成功！', Router::url('admin/brand/categorieslist/'));		    		 
		}else {
			$this->flash('删除失败', Router::url('admin/brand/categorieslist/'));	
        }
	}
	
	public function getnbsp($i) {
	    $str = '';
	    if($i) {
		    for($j=0; $j<$i; $j++) {
			    $str .= "　";
		    }
	    }
	    return $str;
    }

	public function get_dg_category($array,$parentid=0,$level=0,$add=2) {
		$str_pad = $this->getnbsp($level);
		$newarray = array();
		$temp = array();
		foreach($array as $v) {
			if($v['goodscategories']['parent_id'] == $parentid) {
				$newarray[] = array(
					'id' => $v['goodscategories']['id'],
					'cat_name' => $v['goodscategories']['cat_name'],
					'parent_id' => $v['goodscategories']['parent_id'],
					'goods_num' => $v['goodscategories']['goods_num'],
					'sort_order' => $v['goodscategories']['sort_order'],
					'str_pad' => $str_pad
				);
				$temp = $this->get_dg_category($array,$v['goodscategories']['id'],($level+$add));
				if($temp) {
					$newarray = array_merge($newarray, $temp);
				}
			}
		}
		return $newarray;
    }	
	public function get_dg_category_select($array,$parentid=0,$level=0,$add=2) {
		$str_pad = $this->getnbsp($level);
		$newarray = array();
		$temp = array();
		foreach($array as $v) {
			if($v['goodscategories']['parent_id'] == $parentid) {
				$newarray[] = array(
					'id' => $v['goodscategories']['id'],
					'cat_name' => $v['goodscategories']['cat_name'],
					'parent_id' => $v['goodscategories']['parent_id'],
					'goods_num' => $v['goodscategories']['goods_num'],
					'sort_order' => $v['goodscategories']['sort_order'],
					'str_pad' => $str_pad
				);
				//$temp = get_dg_category($array,$v['cat_id'],($level+$add));
				if($temp) {
					$newarray = array_merge($newarray, $temp);
				}
			}
		}
		return $newarray;
    }
	



	
}

?>